package com.cloud_sang.fubai.lb;

import org.springframework.cloud.client.ServiceInstance;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

public class MyBL implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 轮询算法
     * @return
     */
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));//False返回表示实际值不等于预期值。
        System.out.println("****第几次访问，次数next: " + next);
        return next;
    }

    @Override
    public ServiceInstance pollingInstances(List<ServiceInstance> serviceInstances) {

        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

    public ServiceInstance randomInstances(List<ServiceInstance> serviceInstances){
        //这边要判断是否为空的
        return serviceInstances.get(this.chooseRandomInt(serviceInstances.size()));
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

}
